const toolModels = {};

const db = require("../../utils/db");
const uuid = require("uuid");
const moment = require("moment");

/**
 * 获取数据表数据
 * @param {Object} params 请求数据
 * @returns {Object} 响应数据
 */
toolModels.getTable = function (params) {
  return new Promise((resolve, reject) => {
    let sql = `SELECT * FROM system_tool_generate_tables WHERE 1 = 1`;
    sql = getCondition(sql, params);
    let pageNum = Number(params.pageNum);
    let pageSize = Number(params.pageSize);
    sql = `${sql} LIMIT ${(pageNum - 1) * pageSize}, ${pageSize};`;
    db(sql, (err, res) => {
      if (err) {
        reject(err);
      }
      resolve(res);
    });
  });
};

/**
 * 获取数据表总数
 * @param {Object} params 请求数据
 * @returns {Object} 响应数据
 */
toolModels.getTableTotal = function (params) {
  return new Promise((resolve, reject) => {
    let sql = `SELECT COUNT(*) as total FROM system_tool_generate_tables WHERE 1 = 1`;
    sql = getCondition(sql, params);
    db(sql, (err, res) => {
      if (err) {
        reject(err);
      }
      resolve(res[0].total);
    });
  });
};

/**
 *
 * @param {*} sql
 * @param {Object} params 请求数据
 * @returns
 */
const getCondition = function (sql, params) {
  let queryParams = [];
  if (params.tableType) {
    queryParams.push(`tableType = "${params.tableType}"`);
  }
  if (params.tableName) {
    queryParams.push(`tableName LIKE "%${params.tableName}%"`);
  }
  if (params.tableDescribe) {
    queryParams.push(`tableDescribe LIKE "%${params.tableDescribe}%"`);
  }
  if (params.syncStatus) {
    queryParams.push(`syncStatus = "${params.syncStatus}"`);
  }
  if (queryParams.length > 0) {
    sql = `${sql} AND ${queryParams.join(" AND ")}`;
  }
  return sql;
};

/**
 * 获取数据（修改）
 * @param {Object} id 主表id
 * @returns {Object} 响应数据
 */
toolModels.getTableInfo = function (id) {
  return new Promise((resolve, reject) => {
    let sql = `SELECT * FROM system_tool_generate_tables WHERE id = "${id}"`;
    db(sql, (err, res) => {
      if (err) {
        reject(err);
      }
      resolve(res[0]);
    });
  });
};

/**
 * 获取数据（修改）
 * @param {Object} id 主表id
 * @returns {Object} 响应数据
 */
toolModels.getFieldsInfo = function (id) {
  return new Promise((resolve, reject) => {
    let sql = `SELECT * FROM system_tool_generate_fields WHERE tableId = "${id}" ORDER BY \`index\` ASC`;
    db(sql, (err, res) => {
      if (err) {
        reject(err);
      }
      resolve(res);
    });
  });
};

/**
 * 存储数据表
 * @param {Object} params 请求数据
 * @returns {Object} 响应数据
 */
toolModels.addTable = function (params) {
  return new Promise((resolve, reject) => {
    let sql = `INSERT INTO system_tool_generate_tables set?`;
    let value = {
      id: uuid.v4().replaceAll("-", ""),
      tableName: params.tableName,
      tableType: params.tableType,
      tableDescribe: params.tableDescribe,
      tableClassify: params.tableClassify,
      isPaging: params.isPaging,
      isTree: params.isTree,
      version: 1,
      syncStatus: 0,
      updateTime: moment().format("YYYY-MM-DD HH:mm:ss"),
    };
    db(sql, value, (err, res) => {
      if (err) {
        reject(err);
      }
      if (res) {
        resolve(value);
      }
    });
  });
};

/**
 * 存储数据表字段
 * @param {Array} fields 请求数据
 * @param {String} tableId 数据表id
 * @returns {Object} 响应数据
 */
toolModels.addFields = function (fields, tableId) {
  return new Promise(async (resolve, reject) => {
    for (let i = 0; i < fields.length; i++) {
      const fieldInfo = fields[i];
      let value = {
        id: uuid.v4().replaceAll("-", ""),
        tableId: tableId,
        fieldName: fieldInfo.fieldName,
        fieldType: fieldInfo.fieldType,
        fieldLength: fieldInfo.fieldLength,
        fieldDecimal: fieldInfo.fieldDecimal,
        fieldNotes: fieldInfo.fieldNotes,
        fieldDefault: fieldInfo.fieldDefault,
        fieldNotNull: fieldInfo.fieldNotNull,
        fieldPrimarykey: fieldInfo.fieldPrimarykey,
        fieldCharacter: fieldInfo.fieldCharacter,
        fieldCollation: fieldInfo.fieldCollation,
        form: fieldInfo.form,
        table: fieldInfo.table,
        sort: fieldInfo.sort,
        readonly: fieldInfo.readonly,
        required: fieldInfo.required,
        search: fieldInfo.search,
        searchType: fieldInfo.searchType,
        controlType: fieldInfo.controlType,
        controlDefault: fieldInfo.controlDefault,
        dictType: fieldInfo.dictType,
        index: i + 1,
        isEdit: fieldInfo.isEdit,
      };
      try {
        await addField(value);
      } catch (error) {
        reject(error);
      }
    }
    resolve("success");
  });
};
const addField = function (value) {
  return new Promise((resolve, reject) => {
    let sql = "INSERT INTO system_tool_generate_fields set?";
    db(sql, value, (err, res) => {
      if (err) {
        reject(err);
      }
      if (res) {
        resolve(res);
      }
    });
  });
};

/**
 * 删除表格
 * @param {Array} ids 要删除的表格id数组
 * @returns
 */
toolModels.deleteTables = function (ids) {
  return new Promise(async (resolve, reject) => {
    for (let i = 0; i < ids.length; i++) {
      const id = ids[i];
      try {
        await deleteTable(id);
      } catch (error) {
        reject(error);
        return;
      }
    }
    resolve("ok");
  });
};
const deleteTable = function (id) {
  return new Promise((resolve, reject) => {
    let sql = `DELETE FROM system_tool_generate_tables WHERE id='${id}'`;
    db(sql, (fail, res) => {
      if (fail) {
        reject(err);
      }
      if (res) {
        resolve(res);
      }
    });
  });
};
module.exports = toolModels;
